package com.yyang.xiqi;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.yyang.xiqi.utils.HttpUtils;
import com.yyang.xiqi.utils.SpUtils;
import com.yyang.xiqi.utils.StringUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.view.KeyEvent.KEYCODE_BACK;

public class MainActivity extends AppCompatActivity {

    private static String TAG = "MainActivity";

    protected WebView webView;

    protected WebSettings webSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        this.initView();
        this.init();
        boolean enabled = isNotificationListenerEnabled(this);
        if (!enabled) {
            Log.d(TAG, "gotoNotificationAccessSetting");
//            startActivity(new Intent(android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
            gotoNotificationAccessSetting(this);
        }
        Log.d(TAG, String.format("onCreate: %s",enabled));
        String deviceId = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        AppConstants.setDeviceId(deviceId);
//        this.test();

        toggleNotificationListenerService();
        String s = parseMoney("成功收款0.01元。享受免费提现更多");
        Log.d(TAG, "onCreate: parseMoney" + s);
    }

//    @Override
//    protected void onStop() {
//        super.onStop();
//        webSettings.setJavaScriptEnabled(false);
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        webSettings.setJavaScriptEnabled(true);
//    }

    private void initView() {
        String url = SpUtils.getString(this,"notifyUrl");
        String key = SpUtils.getString(this,"key");
//        if (url == null || url.equals("")) {
//            AppConstants.setNotify(false);
//
//        }else {
//            AppConstants.setNotify(true);
//            AppConstants.setNotifyUrl(url);
//            AppConstants.setKey(key);
//        }
        AppConstants.setNotify(true);
        AppConstants.setNotifyUrl(url);
        AppConstants.setKey(key);
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void init() {

        webView = findViewById(R.id.webview);
        //加载网页链接
        webView.loadUrl("https://ggmashang.77pays.org");
        webSettings = webView.getSettings();
//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        // 允许访问localstorage
        webSettings.setDomStorageEnabled(true);
// 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
// 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

//支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

//        webView.setWebChromeClient(new WebChromeClient() {
//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//                super.onProgressChanged(view, newProgress);
//                Log.d("KeithXiaoY","newProgress："+ newProgress );
//            }
//
//            @Override
//            public void onReceivedTitle(WebView view, String title) {
//                super.onReceivedTitle(view, title);
//                Log.d("KeithXiaoY","标题："+ title);
//            }
//        });
        webView.addJavascriptInterface(new JsCallback() {
            @JavascriptInterface//注意:此处一定要加该注解,否则在4.1+系统上运行失败
            @Override
            public void JumpMainAndPostUrlAndKey(String url,String key) {
                changeNotify(url,key);
            }
        },"androidWeihuagu");
    }

    private void changeNotify(String url, String key) {
//        if (AppConstants.getNotify()) {
//            // 关闭通知
//            AppConstants.setNotify(false);
//            AppConstants.setNotifyUrl("");
//            AppConstants.setKey("");
//            SpUtils.putString(this,"notifyUrl",null);
//            SpUtils.putString(this,"key",null);
//        }else {
//            // 开启通知
//            AppConstants.setNotify(true);
//            AppConstants.setNotifyUrl(url);
//            AppConstants.setKey(key);
//            SpUtils.putString(this,"notifyUrl",url);
//            SpUtils.putString(this,"key",key);
//        }
        // 开启通知
//        AppConstants.setNotify(true);
        AppConstants.setNotifyUrl(url);
        AppConstants.setKey(key);
        SpUtils.putString(this,"notifyUrl",url);
        SpUtils.putString(this,"key",key);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //定义回调接口
    public interface JsCallback {
        public void JumpMainAndPostUrlAndKey(String url,String key);
    }

    public boolean isNotificationListenerEnabled(Context context) {
        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
        if (packageNames.contains(context.getPackageName())) {
            return true;
        }
        return false;
    }

    private boolean gotoNotificationAccessSetting(Context context) {

        try {

            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            context.startActivity(intent);

            return true;

        } catch(ActivityNotFoundException e) {

            try {

                Intent intent = new Intent();

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                ComponentName cn = new ComponentName("com.android.settings","com.android.settings.Settings$NotificationAccessSettingsActivity");

                intent.setComponent(cn);

                intent.putExtra(":settings:show_fragment", "NotificationAccessSettings");

                context.startActivity(intent);

                return true;

            } catch(Exception ex) {

                ex.printStackTrace();

            }

            return false;

        }

    }

    private String getSign(HashMap<String,String> data) {
        String sb = "";
        String[] key = new String[data.size()];
        int index = 0;
        for (String k : data.keySet()) {
            key[index] = k;
            index++;
        }
        Arrays.sort(key);
        for (String s : key) {
            sb += s + "=" + data.get(s) + "&";
        }
        sb = sb.substring(0, sb.length() - 1);
        // 将得到的字符串进行处理得到目标格式的字符串
        sb += "&&key=" + "a7f46c3f3d52aa8869a3fe05042e964934e55fda";
//        Log.d(TAG, String.format("getSign: %s",sb));
//        try {
//            sb = URLEncoder.encode(sb, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }// 使用常见的UTF-8编码
//        sb = sb.replace("%3D", "=").replace("%26", "&");
        return StringUtils.md5(sb);
    }

    /**
     * 解析内容字符串，提取金额
     * @param content
     * @return
     */
    private static String parseMoney(String content){
        String pattern = "(\\d+\\.\\d{2})元";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);
        if (m.find()) {
            return m.group(1);
        }
        return "0.00";
    }



    private void toggleNotificationListenerService() {
        PackageManager pm = getPackageManager();

        pm.setComponentEnabledSetting(new ComponentName(this, com.yyang.xiqi.service.HelperNotificationListenerService.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(new ComponentName(this, com.yyang.xiqi.service.HelperNotificationListenerService.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }
}
